<?php
class Merchant_MyAccountController extends Zend_Controller_Action
{

	
	public function init() {//图片上传 取消身份认证
		$action = strtolower($this->_request->getActionName());
		if ($action != 'upload-logo') {
			parent :: init();
		}
	}
	public function preDispatch(){
		$this->tplDirectory = "merchant/myaccount/";		 
		$this->customer = new Zend_Session_Namespace("customer");
		$this->view->customerId=$this->customer->customer['customer_id'];
	}
	 	
	/**
	*
	*
	*/
	public function indexAction(){
        $balance = Merchant_Service_CustomerBalance::getByCustomer($this->customer->customer['customer_id']);
        $this->view->balance =  $balance;
        echo Cff::renderTpl($this->tplDirectory."billing.tpl","user-layout");
	}
	
	public function countUnreadAlertsAction(){
		$customerService = new Merchant_Service_Customer();
		$customerInfo = $customerService->getLoginInfo()->customer;
		$customer_id = $customerInfo['customer_id'];
		if(!$customer_id)return false;
		$cond =array();
		$cond['customer_id'] = $customer_id;
		$cond['alert_status'] = 0;		// alert_status为0 ，末查看
		
		// Notice
		$cond['alert_level'] = 0;
		$unreadNotices = Merchant_Service_Alert::getByCond($cond,'count(*)','',0,0);
		
		// Warning
		$cond['alert_level'] = 1;
		$unreadWarnings = Merchant_Service_Alert::getByCond($cond,'count(*)','',0,0);
		
		//Important
		$cond['alert_level'] = 2;
		$unreadImportants = Merchant_Service_Alert::getByCond($cond,'count(*)','',0,0);
		
		$data =array('ask'=>0,'total'=>0);	
		if( $unreadNotices || $unreadWarnings || $unreadImportants){
			$data['ask'] = 1;
			$data['unread'] = array(
							'notice' => $unreadNotices,
							'warning' => $unreadWarnings,
							'important' => $unreadImportants );
		}
		
		die(json_encode($data));			
	}
		
	/**
	*
	*
	*/
	public function billingAction(){
		$balance = Merchant_Service_CustomerBalance::getByCustomer($this->customer->customer['customer_id']);			
		$this->view->balance =  $balance;
		echo Cff::renderTpl($this->tplDirectory."billing.tpl","user-layout");
	}
	
	/**
	*list of billing detail 
	*
	*/
	public function billingDetailAction(){
	 
		//$balance = Merchant_Service_CustomerBalance::getByCustomer($this->customer);		
		$startTime = $this->_request->getParam('startTime',date('Y-m-d',strtotime("-1 month"))); 
		$endTime =  $this->_request->getParam('endTime',date('Y-m-d'));
		$page = $this->_request->getParam("page",1);
		$pageSize = $this->_request->getParam("pageSize",20);
		$cbh_op_type = $this->_request->getParam('cbh_op_type','');
		$sortColumn = $this->_request->getParam('sortColumn','');
		$sortMethod = $this->_request->getParam('sortMethod','');
		
		$orderby = array('cbh_id DESC');
		if($sortColumn){			
			$orderby = array($sortColumn.' '.$sortMethod);
		}
        $langArr=Common_Service_Get::lang();
        $balanceType=isset($langArr['BALANCE_TYPE'])?$langArr['BALANCE_TYPE']:array();
        unset($langArr);
		$option = array('customer_id'=>$this->customer->customer['customer_id'],'page'=>$page,'pageSize'=>$pageSize);
		$option['startTime'] = $startTime;
		$option['endTime'] = $endTime;
		$option['cbh_op_type'] = $cbh_op_type;

		$count = Merchant_Service_CustomerBalance::getByComdation($option,'count',$orderby);	
        $balanceDetail=array();
        $result['ask']='0';
        if($count[0]['count']>0){
            $balanceDetail = Merchant_Service_CustomerBalance::getByComdation($option,'*',$orderby);
            foreach($balanceDetail as $k =>$val){
                $balanceDetail[$k]['balanceType']=isset($balanceType[$val['cbh_op_type']])?$balanceType[$val['cbh_op_type']]:'Other';
            }
            $result['ask'] = "1";
        }
		$result['count'] = $count[0]['count'];
		$result['data']  = $balanceDetail;
		echo Zend_Json::encode($result);
		 
	}
	
	 /**
	*deposit
	*
	*/
	public function depositAction(){
		
		echo Cff::renderTpl($this->tplDirectory."deposit.tpl","user-layout");
	}
	
	public function depositOrderAction(){
		echo Cff::renderTpl($this->tplDirectory."deposit.tpl","user-layout");
	}
	
	public function comfirmPayAction(){
		echo Cff::renderTpl($this->tplDirectory."deposit.tpl","user-layout");
	}
	
	 public function docheckoutAction(){
		echo Cff::renderTpl($this->tplDirectory."deposit.tpl","user-layout");
    }

	public function accountInfoAction(){
		$customerServiceObj = new Merchant_Service_Customer();
		$customer = &$customerServiceObj->getLoginInfo()->customer;
		$mycustomer = $customerServiceObj->get();
		$customer['customer_logo'] = $mycustomer['customer_logo'];
		$customer['customer_intro'] = $mycustomer['customer_intro'];
		$this->view->customer = $customer;
		$addressService = new Merchant_Service_CustomerAddressBook();
		//公司地址信息
		$companyAdderss = $addressService->get(1);
		//发件地址信息
		$senderAdderss = $addressService->get(3);
		$this->view->companyAdderss = $companyAdderss;
		$this->view->senderAdderss = $senderAdderss;
		if(is_array($senderAdderss)) $this->view->sender = true;
		//查找所有国家
		$countrys = Default_Service_Country::getAll();
		$this->view->countrys = $countrys;
		//当前用户国家
		$currentCountry = Default_Service_Country::getByValue($companyAdderss["cab_country_id"]);
		$this->view->currentCountry = $currentCountry;
		echo Cff::renderTpl($this->tplDirectory.'account-info.tpl','user-layout');
	}
	
	public function modifyPasswordAction() {
		$oldPassword = trim($this->_request->getParam('oldPassword'));
		$password = trim($this->_request->getParam('password'));
		$rePassword = trim($this->_request->getParam('rePassword'));			
		
		$row =array(
				'oldPassword'=>$oldPassword,
				'password'=>$password,
				'rePassword'=>$rePassword
				);
		$error = Merchant_Service_Customer::validateModifyPwd($row);
		if(count($error)){
			$data=array('ask'=>0,'error'=>$error);
			die(Zend_Json::encode($data));
		}else {
			$customerService = new Merchant_Service_Customer();
			$customerInfo = $customerService->getLoginInfo()->customer;
			//重新设置客户密码
			$row =array();
			$row['customer_password'] = Default_Service_Password::getHash($password);
			$res = Merchant_Service_Customer::updateByVal($row,'customer_id',$customerInfo['customer_id']);
								
        	if($res){
        		$data=array('ask'=>1);
				die(Zend_Json::encode($data));
        	}					
		}
		
	}

	public function getSenderAddressAction(){
		$addressService = new Merchant_Service_CustomerAddressBook();
		//发件地址信息
		$senderAdderss = $addressService->get(3);
		die(json_encode($senderAdderss));
	}
	
	public function doPaymentAction(){
		$token = $this->_request->getParam('token');
		$orderId = $this->_request->getParam('orderId');
		$payerId = $this->_request->getParam('payerId');
		$Payer = $this->_request->getParam('payer','payer');
		if(!$orderId||!$token||!$payerId){
				$this->_redirect("/merchant/my-account/deposit");
		}
	    $orders =  Merchant_Service_CustomerDepositOrder::getOrder($orderId);
		$currency = Default_Service_Currency::getByCode($orders['currency_code']);
    	$paymentAmount =  sprintf('%.2f',$orders['currency_value']);
		
		$currencyCode =trim($currency['code']);
		$PaymentAction = 'Sale';
		$ipn = 'http://'.$_SERVER['SERVER_NAME'].'/merchant/my-account/ipn-return/'; 
		$environment = Cff :: getConfig('paypalEnvironment'); 
		$handler = & ProfileHandler_Array::getInstance(array(
															'username' => Cff::getConfig("paypalApiUsername"),
															'certificateFile' => null,
															'subject' => null,
															'environment' => $environment )); 
		$pid = ProfileHandler::generateID(); 
		$profile =  new APIProfile($pid, $handler); 
		$profile->setAPIUsername(Suntek::getConfig("paypalApiUsername"));
		$profile->setAPIPassword(Suntek::getConfig("paypalApiPassword"));
		$profile->setSignature( Suntek::getConfig("paypalApiSignature"));
		$profile->setSubject('payment@chiafulfill.com'); 
		$profile->setEnvironment($environment);
		$caller =& PayPal::getCallerServices($profile);
		$caller->USE_ARRAYKEY_AS_TAGNAME = true;
		$caller->SUPRESS_OUTTAG_FOR_ARRAY = true;
		$caller->OUTTAG_SUPRESS_ELEMENTS = array('PaymentDetailsItem','FlatRateShippingOptions'); 
		$ec_details =& PayPal::getType('DoExpressCheckoutPaymentRequestDetailsType'); 
		$ec_details->setToken($token);
		$ec_details->setPayerID($payerId);
		$ec_details->setPaymentAction($PaymentAction); 
		$amt_type =& PayPal::getType('BasicAmountType');
		$amt_type->setattr('currencyID', $currencyCode);
		$amt_type->setval($paymentAmount, 'iso-8859-1');   
		$payment_details =& PayPal::getType('PaymentDetailsType');
		$payment_details->setOrderTotal($amt_type); 
		$ec_details->setPaymentDetails($payment_details); 
		$ec_request =& PayPal::getType('DoExpressCheckoutPaymentRequestType');
		$ec_request->setDoExpressCheckoutPaymentRequestDetails($ec_details);
		// Execute SOAP request 
		$this->view->currency = $currency;
		if($orders['payment_status']!='PU'){
			$this->view->grossAmount = sprintf("%.2f",$orders['currency_value']);
			$this->loger->info( "paypal>>sent require to Note system!");
			echo Cff::renderTpl('balance/paypal-docheckout.tpl',$this->layout);
			return;
		}
		$response = $caller->DoExpressCheckoutPayment($ec_request);
		$ack = $response->getAck();			
		if ($ack=='Success'||$ack=='SuccessWithWarning')
		{
			$details = $response->getDoExpressCheckoutPaymentResponseDetails();
			$paymentInfo = $details->getPaymentInfo();
			$TransactionID = $paymentInfo->getTransactionID();				
			$amt_obj = $paymentInfo->getGrossAmount();
			$GrossAmount = $amt_obj->_value;
			$GrossAmountCurrency = $amt_obj->_attributeValues['currencyID'];
			$time = date("Y-m-d H:i:s");				 
			$payment_fee=0;
			if($orders['note']!=''){
				$type =2;//不收取手续费
				$note = 'New Order. TransactionID:'.$TransactionID;
			}else{
				$type =1;//收取手续费
				$note = 'Deposit My SFCService Account. TransactionID:'.$TransactionID;
			}
			$payments =PaymentMethodService::get($orders['pm_id']);
			$paymentLog = array(
								'user_id'=>$orders['user_id'],
								'money'=>$orders['currency_value'],
								'reason'=>$note,
								'type'=>1,
								'add_time'=>date('Y-md H:i:s'),
								'currency_id'=>$orders['currency_id'],
								'currency_rate'=>$orders['currencies_present_rate']
								);
			if (UserBalanceService::updatePayment($paymentLog,$orderId,$TransactionID,$payments['ba_id'],$type)) {
					//TODO::send info sfcservice
					 //TODO::send email
				$sentInfo = true;
				$this->loger->info( "paypal>>payment success");
			}
			$this->view->grossAmount = $GrossAmount;
			$this->view->transactionID = $TransactionID;
			$this->view->currency = $currency;
			$this->view->orderId = $orderId;
			$this->view->redirctUrl ='/balance/deposit/';
			if($orders['note']!=''){
				$this->view->redirctUrl ='/order/order/list/status/3';
			}
			echo Cff::renderTpl('balance/paypal-docheckout.tpl',$this->layout); 
		}else{
			$this->loger->info( $response->DoExpressCheckoutPaymentResponseDetailsType->Errors->LongMessage);
			$this->view->message = $response->DoExpressCheckoutPaymentResponseDetailsType->Errors->LongMessage;
			$this->view->backurl = 'merchant/my-account/';
			echo Cff::renderTpl('default/message.tpl','layout-common');
		}
	
	}
	
	public function modifyAccountInfoAction(){
		$firstName = trim($this->_request->getParam("firstName",""));
		$lastName = trim($this->_request->getParam("lastName",""));
		$country = trim($this->_request->getParam("country",""));
		$phone = trim($this->_request->getParam("phone",""));
		$companyName = trim($this->_request->getParam("companyName",""));
		$website = trim($this->_request->getParam("website",""));
		$address = trim($this->_request->getParam("address",""));
		$city = trim($this->_request->getParam("city",""));
		$state = trim($this->_request->getParam("state",""));
		$postalCode = trim($this->_request->getParam("postalCode",""));
		$otherCompanyName = trim($this->_request->getParam("otherCompanyName",""));
		$otherWebsite = trim($this->_request->getParam("otherWebsite",""));
		$otherAddress = trim($this->_request->getParam("otherAddress",""));
		$otherCity = trim($this->_request->getParam("otherCity",""));
		$otherState = trim($this->_request->getParam("otherState",""));
		$otherPostalCode = trim($this->_request->getParam("otherPostalCode",""));
		$returnMethod = trim($this->_request->getParam("returnMethod",""));
		$hasOtherAddress = trim($this->_request->getParam("hasOtherAddress",""));
		$returnMethod = trim($this->_request->getParam("returnMethod",""));
		$customerLogo = trim($this->_request->getParam("company_logo",""));
		$customerIntro = trim($this->_request->getParam("cab_intro",""));
		
		
		$info = array(
			"customer_firstname" => $firstName,
			"customer_lastname" => $lastName,
			"customer_telephone" => $phone,
			"return_package_proccess" => $returnMethod,
			"customer_logo" => $customerLogo,
			"customer_intro" => $customerIntro,
		);
		$address = array(
			"cab_company" => $companyName,
			// "" => $website,
			"cab_street_address1" => $address,
			"cab_city" => $city,
			"cab_state" => $state,
			"cab_postcode" => $postalCode,
			"cab_country_id" => $country,
		);
		$otherAddr = array(
			"cab_company" => $otherCompanyName,
			// "" => $website,
			"cab_street_address1" => $otherAddress,
			"cab_city" => $otherCity,
			"cab_state" => $otherState,
			"cab_postcode" => $otherPostalCode,
		);
		$serviceObj = new Merchant_Service_Customer();
		$addressObj = new Merchant_Service_CustomerAddressBook();
		$customerError = $serviceObj->validateCustomerInfo($info);
		$addressError = $addressObj->validateAddressInfo($address);
		$otherError = array();
		if($hasOtherAddress == 1){
			$otherError = $addressObj->validateAddressInfo($otherAddr);
		}
		$error = array_merge($customerError,$addressError);
		if(!empty($error) || !empty($otherError)){
			$return = array(
				"ask" => false,
				"error" => $error,
				"other" => $otherError
			);
			die(json_encode($return));
		}
		
		$serviceObj->update($info);
		$addressObj->update($address,1);
		if($hasOtherAddress == 0){
			$otherAddr['cab_type'] = 0;
			$addressObj->delete($otherAddr,3);
		}else{
			$addressObj->update($otherAddr,3);
		}
		$return = array(
			"ask" => true
		);
		die(json_encode($return));
		
	}
	
	public function dashboardAction(){
		echo Cff::renderTpl($this->tplDirectory.'dashboard.tpl','user-layout');
	}
	
	public static function logError($error){
		$logger = new Zend_Log();
		$uploadDir = '/var/www/CFF/front/data/log/test.log';
		$writer = new Zend_Log_Writer_Stream($uploadDir.'shipRate4.log');
		$logger->addWriter($writer);
		$logger->info(date('Y-m-d H:i:s').': '.$error." \n");
	}
	
	public function uploadLogoAction(){
		$tempFile = $_FILES['picture']['tmp_name'];
		//获得图片存储的临时位置
		$serviceObj = new Merchant_Service_Product();
		$str = var_export($tempFile,true);
		self::logError($str);
	
		$targetDir = $serviceObj->getPictureUploadDir($this->_request->customerId);
		$targetFile =  $targetDir ."/". $_FILES['picture']['name'];
		$logoName = "____________logo.jpg";
		$targetFile =  $targetDir ."/$logoName";
	
		$arr = array("ask"=>0);
		if(move_uploaded_file($tempFile,$targetFile)){
				
			$arr = array("ask"=>1,					
					"filepath"=>"/merchant/my-account/view-logo/fileName/".$_FILES['picture']['name'],
					"fileName"=>$_FILES['picture']['name'],
			);
			$arr = array("ask"=>1,
					"filepath"=>"/merchant/my-account/view-logo/fileName/$logoName",
					"fileName"=>"$logoName",
			);
				
		}else{
			$arr = array("ask"=>0,"error"=>'Inner Error');
		}
		echo json_encode($arr);
		exit;
	}
	
	public function viewLogoAction(){		
		$fileName = $this->_request->fileName;
		$serviceObj = new Merchant_Service_Product();
		$targetDir = $serviceObj->getPictureUploadDir($this->customer->customerId);
// 		echo $targetDir ."/". $fileName;exit;
		header('Content-Type: image/jpeg');
		if(file_exists($targetDir ."/". $fileName)){
			echo file_get_contents($targetDir ."/". $fileName);			
		}else{
			echo file_get_contents("../public/images/noimg.jpg");
			
		}
		exit;
	}
}